const fs = require('fs')

//取决于最终在哪里调用为基准 dao -> router -> app.use(router)
const DB_Path = require('path').join(__dirname, '../db.json')

let query = cb => {
  fs.readFile(DB_Path, 'utf8', (err, data) => {
    if(err) return cb(err)
    cb(null, JSON.parse(data).students)
  })
}

let queryById = (id, cb) => {
  query((err,data) => {
    if(err) return cb(err)
    cb(null, data.filter(i => i.id == id)[0])
  })
}

let add = (stu, cb) => {
  query((err,data) => {
    if(err) return cb(err)
    stu.id = data[data.length - 1].id + 1
    data.push(stu)
    insert(data, err => {
      if(err) cb(err)
      cb(null)
    })
  })
}

let update = (stu, cb) => {
  query((err, data) => {
    if(err) return cb(err)
    let oldStu = data.find(r => r.id == stu.id)
    let oldIndex = data.findIndex(r => r.id == stu.id)
    data.splice(oldIndex,1,stu)
    insert(data, err => {
      if(err) cb(err)
      cb(null)
    })
  })
}

let deleteStu = (id, cb) => {
  query((err,data) => {
    if(err) return cb(err)
    let index = data.findIndex(r => r.id == id)
    data.splice(index, 1)
    insert(data, err => {
      if(err) cb(err)
      cb(null)
    })
  })
}

let insert = (data, cb) => {
  fs.writeFile(DB_Path, JSON.stringify({students : data}), err => {
    if(err) return cb(err)
    cb(null)
  })
}

module.exports = {
  query,
  queryById,
  add,
  update,
  deleteStu
}
